package com.example.qqviewspringboot.controller;

import com.example.qqviewspringboot.data.User;
import com.example.qqviewspringboot.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping("/api/users")
public class AvatarController {

    @Value("${avatar.storage.path}")
    private String avatarStoragePath;

    @Value("${avatar.base.url}")
    private String avatarBaseUrl;

    private final UserService userService;

    @Autowired
    public AvatarController(UserService userService) {
        this.userService = userService;
    }

    /**
     * 上传用户头像
     *
     * @param userId 用户ID
     * @param file   头像图片文件
     * @return 响应实体
     */
    @PostMapping(value = "/{userId}/avatar", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public ResponseEntity<?> uploadAvatar(@PathVariable Long userId, @RequestPart("file") MultipartFile file) {
        // 验证文件是否为空
        if (file.isEmpty()) {
            return ResponseEntity.badRequest().body("未选择上传的文件。");
        }

        // 验证文件类型（仅允许图片）
        String contentType = file.getContentType();
        if (contentType == null || !contentType.startsWith("image/")) {
            return ResponseEntity.badRequest().body("仅支持图片文件的上传。");
        }

        try {
            // 使用 UserServiceImpl 上传头像并获取头像URL
            String avatarUrl = userService.uploadAvatar(userId, file);

            // 获取更新后的用户信息
            User user = userService.getUserInfo(userId)
                    .orElseThrow(() -> new RuntimeException("用户未找到"));

            return ResponseEntity.ok(user);
        } catch (IllegalArgumentException e) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(e.getMessage());
        } catch (RuntimeException e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(e.getMessage());
        }
    }

    /**
     * 上传用户背景图片
     *
     * @param userId 用户ID
     * @param file   背景图片文件
     * @return 响应实体
     */
    @PostMapping(value = "/{userId}/background", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public ResponseEntity<?> uploadBackground(@PathVariable Long userId, @RequestPart("file") MultipartFile file) {
        // 验证文件是否为空
        if (file.isEmpty()) {
            return ResponseEntity.badRequest().body("未选择上传的文件。");
        }

        // 验证文件类型（仅允许图片）
        String contentType = file.getContentType();
        if (contentType == null || !contentType.startsWith("image/")) {
            return ResponseEntity.badRequest().body("仅支持图片文件的上传。");
        }

        try {
            // 使用 UserServiceImpl 上传背景图片并获取背景URL
            String backgroundUrl = userService.uploadBackground(userId, file);

            // 获取更新后的用户信息
            User user = userService.getUserInfo(userId)
                    .orElseThrow(() -> new RuntimeException("用户未找到"));

            return ResponseEntity.ok(user);
        } catch (IllegalArgumentException e) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(e.getMessage());
        } catch (RuntimeException e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(e.getMessage());
        }
    }

}
